<template>
  <div style="width:100;height:100%" :id="id">
    <Portal to="right-disable"
            style="width:100;height:100%"
            v-loading="loading"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 style="width:100%;height: 100%;border:0"
                 class="el-card content-card">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <!-- <div class="title"
               :style="{backgroundImage:'url('+gadgetSetting.backgroundImg+')',fontSize:gadgetSetting.titleStyle.size,color:gadgetSetting.titleStyle.color}">
            {{ gadgetSetting.title }}
          </div> -->
            <div align="center"
                 style="width:100%;height:100%">
              <div v-if="isHasData"
                   @click="onClick"
                   :id="selfGadgetUuid"
                   :key="isHasData"
                   style="width:100%;height:100%;"
                   :style="{'zoom':zoomValue}"></div>
              <div v-else
                    class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
              </div>
            </div>
          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import * as Echarts from 'echarts'
import { getUUID } from '@/utils'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { formatFunction } from '@/utils/format'
export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      selfGadgetUuid: getUUID(),
      currentTime: null,
      queryData: [],
      queryFields: [],
      value: 0,
      datesource: {
        value: 0
      },
      gadgetSetting: null,
      loading: false,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'processgaugegadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'processgaugegadget' }).gadgetSetting
          // gadgetSetting: {
          //   title: 'Progress',
          //   titleStyle: { size: '14px', color: '#fff' },
          //   color: '#e5ce20',
          //   valueFontSize: '40',
          //   startText: '',
          //   endText: '',
          //   maximum: 150,
          //   minimum: 0,
          //   backgroundImg: 'https://oss.mspbots.ai/app/gadget/card-number-title-black.png',
          //   valueFieldsName: 'value',
          //   headerTitle: '',
          //   headerDescription: ''
          // }
        }
      },
      ranges: [
        {
          start: 0,
          end: 100,
          radius: '90%',
          startWidth: 30,
          endWidth: 30,
          color: '#E0E0E0',
          roundedCornerRadius: 20
        }
      ],
      majorTicks: {
        width: 0
      },
      animation: {
        enable: false
      },
      pointerRadius: '90%',
      type: 'RangeBar',
      gaugeRadius: '90%',
      startAngle: 200,
      endAngle: 160,
      lineStyle: { width: 0 },
      minorTicks: {
        width: 0
      },
      annotations: [{
        content: '',
        angle: 0,
        zIndex: '1',
        radius: '0%'
      }
      ],
      labelStyle: {
        position: 'Inside',
        useRangeColor: true,
        font: { size: '0px', color: 'white', fontFamily: 'Roboto', fontStyle: 'Regular' }
      },
      numberVal: 0,
      chartWidth: '500',
      chartHeight: '500',
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      chartDom: null,
      repeatNumber: 0,
      gadgetWidth: null,
      echartsOption: {
        title: {},
        series: [{
          type: 'gauge',
          radius: '80%',
          min: 0,
          max: 100,
          axisLine: {
            lineStyle: {
              width: 25,
              color: [
                [0.3, '#67e0e3'],
                [0.7, '#37a2da'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            distance: -30,
            length: 8,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          splitLine: {
            distance: -30,
            length: 30,
            lineStyle: {
              color: '#fff',
              width: 4
            }
          },
          axisLabel: {
            color: 'auto',
            distance: 40,
            fontSize: 20
          },
          detail: {
            fontSize: 25,
            valueAnimation: true,
            formatter: '{value}',
            color: 'auto'
          },
          data: []
        }]
      },
      linkedDatasetList: []
    }
  },
  computed: {
    zoomValue () {
      return this.pageFromType === 'report'?this.rolHeight/80:this.gadgetHeight / 500
    }
  },
  // provide: {
  //   circularGauge: [Annotations]
  // },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :(this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', this.query)
    this.$store.state.isWidget = false
  },
  updated () {
    if (document.getElementById(`${this.selfGadgetUuid}`) && document.getElementById(`${this.selfGadgetUuid}`).offsetWidth) {
      let wW = document.getElementById(`${this.selfGadgetUuid}`).offsetWidth
      let wH = document.getElementById(`${this.selfGadgetUuid}`).offsetHeight
      this.gadgetSetting.titleFontSize = (parseInt(wW / 70) + parseInt(wH / 200))<10?'10px':(parseInt(wW / 70) + parseInt(wH / 200) + 'px')
    }
  },
  methods: {
    updateChart (originData) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else {
        this.gadgetWidth = this.chartDom.clientWidth
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        this.echartsOption.title.textStyle = { fontSize: this.gadgetSetting.titleFontSize || 18 }
        this.echartsOption.series[0].data = [{ value: originData[0][this.gadgetSetting.valueFieldsName] }]
        this.echartsOption.series[0].detail.formatter = '{value} ' + this.gadgetSetting.suffix
        this.echartsOption.series[0].detail.fontSize = this.gadgetSetting.xAxisFontSize?this.gadgetSetting.xAxisFontSize:'20'
        this.echartsOption.series[0].min = this.gadgetSetting.minimum || 0
        this.echartsOption.series[0].max = this.gadgetSetting.maximum || 1
        this.echartsOption.series[0].name = this.gadgetSetting.valueFieldsName
        this.setColors(this.echartsOption)
        this.echartsOption.series[0].axisLabel.formatter = (value) => {
           let rich = this.echartsOption.series[0].axisLabel.rich
           let unit
            if (Number(value) > 999) {
             unit =  formatFunction('number', value, {
              fieldsNewFormat: {
                decimals: 1,
                fieldsNewFormatType: 'number',
                option: 'abbreviate',
                prefix: ''
              }
            })
          } else {
            unit = value
          }
            if(rich&&rich[value*100]) {
              return `{${value * 100}|${unit}}`
            } else {
              return unit
            }
        }
        // myChart.resize({
        //   width: chartDom.clientWidth,
        //   height: chartDom.clientHeight
        // })
        this.echartsOption.series[0].detail.formatter = (value) => {
          return `${this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsName)}  ${this.gadgetSetting.suffix}`
        }
        myChart.setOption(this.echartsOption)
        this.$erd.listenTo(this.chartDom, element => {
          this.$nextTick(() => {
            this.resized()
          })
        })
        this.loading = false
      }
    },
    setColors (echartsOption) {
      let color = [
        '#5c7bd9',
        '#9fe080',
        '#ffec92',
        '#ff7070',
        '#7ed3f4',
        '#40b27d',
        '#ff915a',
        '#a969c6',
        '#fe87df'
      ]
      try {
        this.echartsOption.series = echartsOption.series.map(vp => {
          let setColor = [[1, color[0]]]
          let arr = this.gadgetSetting.Thresholds && Array.isArray(JSON.parse(this.gadgetSetting.Thresholds)) ? JSON.parse(this.gadgetSetting.Thresholds).filter(v => v.value && v.value >= vp.min && v.value <= vp.max) : []
          let equalArr = this.gadgetSetting.Thresholds && Array.isArray(JSON.parse(this.gadgetSetting.Thresholds)) ? JSON.parse(this.gadgetSetting.Thresholds).filter(v => v.value && v.value >= vp.min && v.value <= vp.max).filter(ii=>ii.operator==='=') : []
          let greaterEqualArr = this.gadgetSetting.Thresholds && Array.isArray(JSON.parse(this.gadgetSetting.Thresholds)) ? JSON.parse(this.gadgetSetting.Thresholds).filter(v => v.value && v.value >= vp.min && v.value <= vp.max).filter(ii=>ii.operator==='>=') : []
          if (arr.length) {
            let tempArr = [...new Set([...arr.map(v => v.value), vp.max])].sort((a, b) => a - b).map(v => [v, ''])
            arr.sort((a, b) => a.value - b.value).forEach(v => {
              let index = tempArr.findIndex(e => e[0] === v.value)
              if (v.operator === '>' || v.operator === '>=') {
                for (let i = index + 1; i < tempArr.length; i++) {
                  tempArr[i][1] = v.color
                }
              }
              if (v.operator === '<' || v.operator === '<=') {
                for (let i = 0; i <= index; i++) {
                  tempArr[i][1] = v.color
                }
              }
            })
            setColor = tempArr.map(v => [(v[0] - vp.min) / (vp.max - vp.min), v[1]])
          }
          vp.axisLine = {
            lineStyle: {
              color: setColor
            }
          }
          let richObj = {}
          if(greaterEqualArr.length > 0 ) {
            greaterEqualArr.forEach(item=>{             
              richObj[item.value * 100] = {
                color: item.color,
                fontSize: 20
              }
            }) 
            vp.axisLabel.rich = richObj
          }
          if(equalArr.length === 1 && vp.data[0].value === equalArr[0].value * 1) {
            vp.detail.color = equalArr[0].color
            vp.pointer.itemStyle.color= equalArr[0].color         
          } else if (greaterEqualArr.length > 0 && greaterEqualArr.filter(item=>item.value * 1===vp.data[0].value).length>0) {
            const arr = greaterEqualArr.filter(item=>item.value * 1===vp.data[0].value)
            vp.detail.color = arr[0].color
            vp.pointer.itemStyle.color= arr[0].color 
          } else {
            vp.detail.color = 'auto'
            vp.pointer.itemStyle.color= 'auto'    
          }
          return vp
        })
      } catch (error) {
        console.log(error)
      }
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 5) + 'px'
      this.chartHeight = (newHPx - 5) + 'px'
    },
    onClick () {
      let data = ''
      var pointx = ''
      pointx = this.datesource[this.queryDrillthrough.alias]
      if (!pointx && pointx !== false && pointx !== 0) {
        pointx = ' is null'
      } else {
        pointx = "='" + pointx + "'"
      }
      if (this.queryDrillthrough.dataType === 'dimension') {
        data = '"' + this.queryDrillthrough.field + '"' + pointx// "='" + this.datesource[this.queryDrillthrough.alias] + "'"
      }
      this.findOriginData(data)
    },
    load () {
      this.circulargauge = this.$refs.circulargauge
      this.gadgetHeight = this.gadgetInfo.h * 20 - 20
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    query (e) {
      if (e !== 'auto') {
        this.loading = true
        this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        if (res.data) {
          _self.queryData = res.data
        }
        if (res.config) {
          if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
              _self.gadgetSetting =  this.dataInfo.gadgetSetting
            }else{
              _self.gadgetSetting = _self._.merge(_self.gadgetSetting, res.config)
          }
         
        }
        if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
          _self.gadgetSetting.headerDescription = ''
        }
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
           _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        let tempDataList = res.data
        let objList = res.selectFields.find(item => { return item.dataType === 'dimension' })
        _self.queryDrillthrough = objList || {}
        _self.queryId = _self.queryDrillthrough ? _self.queryDrillthrough.queryId : ''
        _self.datesource[_self.gadgetSetting.valueFieldsName] = tempDataList[0][_self.gadgetSetting.valueFieldsName]
        if (_self.queryDrillthrough) {
          _self.datesource[_self.queryDrillthrough.alias] = tempDataList[0][_self.queryDrillthrough.alias]
          var tempAlias = _self.datesource[_self.queryDrillthrough.alias]
          if (!tempAlias) {
            _self.queryDrillthrough.alias = 'dimension1'
            _self.datesource[_self.queryDrillthrough.alias] = tempDataList[0][_self.queryDrillthrough.alias]
          }
        }
        _self.linkedDatasetList = res.datasetSync
        _self.queryFields = res.selectFields
        _self.updateChart(res.data)
      }).catch((error) => {
        if (this.wName) {
          this.widgetName = this.wName
          }
        Echarts.init(this.chartDom).dispose()
        this.isHasData = false
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.currentTime = new Date()
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 45%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
  width: 100%;
  height: 100%;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardTitle {
  font-size: 16px;
  color: #000;
  font-weight: 700;
  display: inline-block;
  max-width: calc(100% - 30px);
  position: relative;
  top: 2px;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.valuecss {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  z-index: 50;
  display: flex;
  justify-content: center;
  align-items: center;
}

.title {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
  padding: 5px;
}

.el-card {
  padding: 0 !important;
}

#circulargauge_control_1_CircularGaugeBorder {
  height: 100%;
}
</style>
